//app.js
const config = require('./config');
const host = config.host;
App({
  globalData: {
    userInfo: null,
    webUserInfo: null,
    formIDs:[],
  },
  onLaunch: function() {
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    this.setPageTitle("盛基商品信息采集")
  },

  getUserInfo: function(cb) {
    var that = this
    if (that.globalData.userInfo) {
      typeof cb == "function" && cb(that.globalData.userInfo)
    } else {
      //调用登录接口
      wx.getUserInfo({
        withCredentials: false,
        success: function(res) {
          that.globalData.userInfo = res.userInfo
          typeof cb == "function" && cb(that.globalData.userInfo)
        }
      })
    }
  },
  /**
   * 获取用户openid
   */
  getOpenID:function(cb){
    var that = this
    wx.login({
      success: function (res) {
        // 向后台发送请求，用户code换取openid
        wx.request({
          url: host+"/wxapp/index/getOpenID",
          method: 'get',
          data: {
            code: res.code
          },
          header: { "Content-Type": "application/json" },
          success: function (r) {
            if (r.data.ok == true) {
              that.globalData.userInfo.openID = r.data.content.res.openid
              cb(r.data.content.res.openid)
            } else {
              wx.showToast({
                title: '获取用户信息失败！',
              })
            }
          },
					fail:function(){
						console.log("getOpenID failed")
					}
        })
      }
    })
  },
  /**
   * 获取用户信息
   */
  getWebUserInfo:function(openID,nickName,headPic,cb){
    var that = this
    wx.request({
      url: host+'/wxapp/index/getUserInfo',
      data: {
        openID: openID,
        nickName:nickName,
        headPic:headPic
      },
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.ok == true) {
          that.globalData.webUserInfo = res.data.content.userInfo
          typeof cb == "function" && cb(res.data.content.userInfo)
          console.log(that);
        } else {
          cb(null)
        }
      },
			fail:function(){
				console.log("getWebUserInfo failed")
			}

    })
  },
	// 设置标题
	setPageTitle: function (title) {
		wx.setNavigationBarTitle({
			title: title
		});
	},
  /**
   * 发送竞价信息
   */
	doSendPrice:function(uid,goodsPrice,goodsID,cb){
		var pattern = /^\d*\.*\d{0,2}$/
		var flag = pattern.test(goodsPrice);
		if (!flag) {
			wx.showToast({
				title: '格式不正确！',
				image: "../../images/error2.png",
				duration: 2000
			})
			return
		}
		wx.request({
			url: host + '/wxapp/order/savePrice',
			data: {
				uid: uid,
				goodsPrice: goodsPrice,
				goodsID: goodsID
			},
			method: "POST",
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			success: function (res) {
        console.log(res);
				if (res.data.ok == true) {
					wx.showToast({
						title: '出价成功！',
					})
          typeof cb == "function" && cb()
        } else{
          wx.showToast({
            title: res.data.msg,
            image: "../../images/error2.png"
          })
        } 
			}
		})
	},
	/**
   * 发起支付保证金
   */
	payDeposit: function () {
		var that = this
		var openID = that.globalData.userInfo.openID
		if (openID) {
			// 发起支付请求
			wx.request({
				url: host + '/wxapp/index/order',
				header: {
					'content-type': 'application/x-www-form-urlencoded'
				},
				data: {
					openID: openID
				},
				method: 'POST',
				success: function (response) {
          console.log("response",response);
					wx.requestPayment({
						timeStamp: response.data.content.result.timeStamp,
						nonceStr: response.data.content.result.nonceStr,
						package: response.data.content.result.package,
						signType: response.data.content.result.signType,
						paySign: response.data.content.result.paySign,
						success: function (res) {
							// 付款成功 更新用户信息
							wx.request({
								url: host + '/wxapp/index/getUserInfo',
								data: { openID: that.globalData.userInfo.openID },
								method: "POST",
								header: {
									'content-type': 'application/x-www-form-urlencoded'
								},
								success: function (r) {
									that.globalData.webUserInfo = r.data.userInfo
									wx.switchTab({
										url: '../index/index',
									})
								}
							})
						},
						fail: function (res) {
							console.log(res)
						}
					})
				}
			})
		}

	},
  /**
   * 收集formID
   */
  collectFormID:function(formID){
    var formIDs = this.globalData.formIDs
    formIDs.push(formID)
    this.globalData.formIDs = formIDs
  },
  /**
   * 发送formIDs
   */
  sendFormIDs:function(){
    var that = this
    var openID = that.globalData.userInfo.openID
    var formIDs = that.globalData.formIDs
    // 如果用户openid存在 且 formIDs 存在
    if(typeof(openID)=="string" && formIDs.length>0){
      that.globalData.formIDs = []
      wx.request({
        url: host+"/wxapp/index/saveFormID",
        data: { openID: openID,formIDs:formIDs },
        method: "POST",
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          console.log(res.data)
        }
      })
    }
  }


})
